<?php defined('SYSPATH') or die('No direct script access.');

// URL: /<context>/index.php/Home/
class Controller_Public extends Controller_Base 
{
	private $categoryService;
	private $profileService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		
		$this->categoryService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_CATEGORY.'/', ACCESS_TOKEN);
		$this->categoryService->init($this->_requestContext);

		$this->profileService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_PROFILE.'/', ACCESS_TOKEN);
		$this->profileService->init($this->_requestContext);

		$this->logger = Logger::getLogger("seednia");

		// in public there is no xid, so the xid is actually action name
		$action = $request->param('xid');
		$request->action($action);

	}
	
	public function action_index()
	{
		// bypass $this->index
		$content = View::factory($this->_theme.'/site_initial');
		$this->template->content = $content;
	}
	
	public function action_signup()
	{
		if ($this->isMethodGet()) {
			$this->showSignupForm();
		} else if ($this->isMethodPost()) {
			$this->doSignup();
		}
	}
	
	/**
	 * If GET then show form,
	 * If POST then process login
	 * @pre 
	 * @post
	 */
	public function action_login()
	{
		if ($this->isMethodGet()) {
			$this->showLoginForm();
		} else if ($this->isMethodPost()) {
			$this->doProcessLoginForm();
		}
	}
	
	private function showLoginForm()
	{
		$this->template->title = __('Seednia Login');
			
		$isFail = $this->request->query('status');
		$content = View::factory($this->_theme.'/user_login');
		$this->template->content = $content;
	}
	
	private function doProcessLoginForm()
	{
		try {
			$id = $this->request->post('id');
			$password = $this->request->post('password');
			$params = array('id'=>$id, 'password'=>$password);
			$user = $this->_profileHelper->getUserService()->get($params, "login");
			if ($user != null && isset($user->paramsText)) {
				$user->params = json_decode($user->paramsText, true);
			}
			
			$redirTo = null;
			if ($user != null) { // login success
				// Save in the session instance
				$this->logger->debug("Login success [".$id.'/'.$password.']');
				$session = Util_Session::setUserInfo($user);
				
				if (isset($user->activeProjectSid)) {
					Util_Session::set(SNAME_PROJECT_SID, $user->activeProjectSid);
				} else {
					Util_Session::set(SNAME_PROJECT_SID, -2);
				}
					
				$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Home';
			} else { // login fail
				//$this->logger->debug("Login fail [".$id.'/'.$password.']');
				Util_Session::set('login_fail_count', 1);
				$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/'.$this->request->controller().'/signup?login=fail';	
			}

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	public function action_logout()
	{
		//Util_Session::delete(SNAME_USER);
		//Util_Session::delete(SNAME_PROJECT_SID);
		Util_Session::destroy();
		$redirTo = CONTROLLERPAGE.'/Public';
		$this->request->redirect($redirTo);
	}
		
	private function showSignupForm()
	{
		$this->template->title = __('Seednia Sign Up');
			
		$isFail = $this->request->query('status');
		$content = View::factory($this->_theme.'/user_registpage');
		
		$login = $this->request->query('login');
		if ($login == 'fail') {
			$content->message = 'Login failed.<br />If you have not signed up yet, you can do now. It\'s free';
		}
		
		$this->template->content = $content;
	}

	public function doSignup()
	{
		try {
			$record = array();
			$creatorDto = array();
			
			$creatorDto['originalDomainId'] = $this->_requestContext->domainId;
			$creatorDto['domainId'] = $this->_requestContext->domainId;
			$creatorDto['email'] = $this->request->post('email');
			// TODO: make it choosable
			$creatorDto['displayName'] = $this->request->post('firstName').' '. $this->request->post('lastName');
			$creatorDto['id'] = $creatorDto['email'];
			$creatorDto['password'] = $this->request->post('password');
			$record['creatorDto'] = $creatorDto;
			
			$record['firstName'] = $this->request->post('firstName');
			$record['lastName'] = $this->request->post('lastName');
			
			$wantTo_pursue = $this->request->post('wantTo_pursue');
			$wantTo_mentor = $this->request->post('wantTo_mentor');
			$wantTo_collaborate = $this->request->post('wantTo_collaborate');
			$wantTo_coordinate = $this->request->post('wantTo_coordinate');
			$wantTo = $wantTo_pursue | $wantTo_mentor | $wantTo_collaborate | $wantTo_coordinate;
			$record['wantTo'] = $wantTo;
			
			$errorMessage = null;

			$params = array('id' => $creatorDto['id']);
			$user = $this->_profileHelper->getUserService()->getList($params, 0, 1);
			if ($user == null) {
				$params = array('email' => $creatorDto['email']);
				$user = $this->_profileHelper->getUserService()->getList($params, 0, 1);
				if ($user != null) {
					$errorMessage = "Email already taken";
				}
			} else {
				$errorMessage = "ID already taken";
			}
			
//echo Debug::vars($user);

			$redirTo = null;
			if ($user == null) { // ID is available
				//$sid = $this->userService->add($record);
				$sid = $this->profileService->add($record);
				
				$profile = $this->profileService->getByXid($sid);
				
				if ($profile != null) {
					$session = Util_Session::setUserInfo($profile->creatorDto);
				} else {
					// Some error???
				}

				$redirTo = CONTROLLERPAGE.'/Home';
			} else { // id not available
				$session = Session::instance();
				Util_Session::set('error_message', $errorMessage);
				$redirTo = CONTROLLERPAGE.'/Public/?status=fail';					
			}

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
			die($ex);
		}
	}
	
	
} // End Controller_Home